import React, { useCallback, useEffect, useState } from "react";
import /*RFValue*/ "react-native-responsive-fontsize";
import * as S from "./styles";
import {
  Text,
  TouchableOpacityProps,
  Image,
  StyleSheet,
  ScrollView,
  Alert,
} from "react-native";
import { getEventList, getCommonEventList } from "../../services";
import { ImageMap } from "../../constants/categories";
import { useCategory } from "../../hooks/useCategory";
import { useTasks } from "../../hooks/useTasks";
import moment from "moment";
import { showToast } from "../../utils/toast";

export interface ButtonProps extends TouchableOpacityProps {
  children: string;
  type?: string;
  active?: boolean;
}

export const CategoryBtn = ({
  type,
  active = false,
  children,
  ...rest
}: ButtonProps) => {
  const url = ImageMap.find((image) => {
    return image.name === type;
  })?.url;
  return (
    <S.ButtonContainer onPress={rest.onPress} activeOpacity={0.7} {...rest}>
      {type && url && (
        <Image
          source={url}
          style={{
            width: /*RFValue*/ 20,
            height: /*RFValue*/ 20,
          }}
        />
      )}
      <S.ButtonText
        numberOfLines={1}
        ellipsizeMode="tail"
        style={active && { color: "rgba(65, 79, 102, 1)" }}
      >
        {children}
      </S.ButtonText>
    </S.ButtonContainer>
  );
};

const Category2Btn = ({ children, active, ...rest }: ButtonProps) => {
  return (
    <S.Button2Container onPress={rest.onPress} activeOpacity={0.7} {...rest}>
      <S.Button2Text style={active && { color: "rgba(65, 79, 102, 1)" }}>
        {children}
      </S.Button2Text>
    </S.Button2Container>
  );
};

export const Category = () => {
  const [selectedValue, setSelectedValue] = useState(null);
  const [selectedCategory2, setSelectedCategory2] = useState(null);
  const [selectedCategory3, setSelectedCategory3] = useState(null);
  const [selectedCommonCategory, setSelectedCommonCategory] = useState(null);
  const {
    categorys,
    updateSelectedCategoryId,
    loadCategory,
    commonCategorys,
    loadCommonCategory,
    selectedStatus,
    updateSelectedStatus,
    resetSelected,
    updateResetSelected,
  } = useCategory();
  const { updateSelectedMood, updateSelectedTime } = useTasks();

  useEffect(() => {
    loadCategory();
    loadCommonCategory();
  }, []);

  useEffect(() => {
    if (!selectedStatus) {
      // setSelectedValue(null);
      // setSelectedCategory2(null);
      if (selectedCategory3) {
        setSelectedCategory3(null);
      }
      if (selectedCategory2 && !selectedCategory3) {
        setSelectedCategory2(null);
      }
      setSelectedCommonCategory(null);
      updateSelectedCategoryId(null);
      updateSelectedStatus(true);
    }
    if (resetSelected) {
      setSelectedValue(null);
      setSelectedCategory2(null);
      setSelectedCategory3(null);
      setSelectedCommonCategory(null);
      updateSelectedCategoryId(null);
      updateSelectedStatus(true);
      updateResetSelected(false);
    }
  }, [selectedStatus, resetSelected]);

  return (
    <S.Container>
      <ScrollView horizontal showsHorizontalScrollIndicator={false}>
        <S.ButtonsWrapper>
          {categorys &&
            categorys.map((category) => {
              return (
                <CategoryBtn
                  onPress={() => {
                    setSelectedValue(
                      selectedValue === category ? null : category
                    );
                    setSelectedCategory2(null);
                    setSelectedCategory3(null);
                    setSelectedCommonCategory(null);
                    updateSelectedCategoryId({ ...category, eventType: 1 });
                    if (selectedValue === category) {
                      updateSelectedCategoryId(null);
                    }
                    updateSelectedMood(undefined);
                    updateSelectedTime(undefined);
                    // updateQuickVisible(false);
                  }}
                  key={category.id}
                  type={category.icon}
                  active={selectedValue?.id === category.id}
                  style={selectedValue?.id === category.id && styles.selected}
                >
                  {category.name}
                </CategoryBtn>
              );
            })}
        </S.ButtonsWrapper>
      </ScrollView>
      {selectedValue?.children?.length > 0 && (
        <S.Container2
          style={
            selectedCategory2 && selectedCategory2.children.length
              ? {
                  paddingBottom: 0,
                }
              : { paddingBottom: /*RFValue*/ 16 }
          }
          horizontal
          showsHorizontalScrollIndicator={false}
        >
          <S.Buttons2Wrapper>
            <Text
              style={{
                fontFamily: "HarmonyOS_Sans_SC_Regular",
                fontSize: /*RFValue*/ 12,
                marginRight: /*RFValue*/ 16,
                color:'#000'
              }}
            >
              二级
            </Text>
            {categorys && categorys
              .find((category) => category.id === selectedValue?.id)
              ?.children.map((category2, index) => {
                return (
                  <Category2Btn
                    key={index}
                    style={
                      selectedCategory2 &&
                      selectedCategory2.id == category2.id &&
                      styles.selected2
                    }
                    active={
                      selectedCategory2 && selectedCategory2.id == category2.id
                    }
                    onPress={() => {
                      setSelectedCategory2(
                        selectedCategory2 === category2 ? null : category2
                      );
                      setSelectedCategory3(null);
                      setSelectedCommonCategory(null);
                      if (selectedCategory2 !== category2) {
                        updateSelectedCategoryId({
                          ...category2,
                          eventType: 2,
                        });
                      } else {
                        updateSelectedCategoryId({
                          ...selectedValue,
                          eventType: 1,
                        });
                      }
                    }}
                  >
                    {category2.name}
                  </Category2Btn>
                );
              })}
          </S.Buttons2Wrapper>
        </S.Container2>
      )}

      {selectedCategory2 && selectedCategory2.children.length > 0 && (
        <S.Container3 horizontal showsHorizontalScrollIndicator={false}>
          <S.Buttons2Wrapper>
            <Text
              style={{
                fontFamily: "HarmonyOS_Sans_SC_Regular",
                fontSize: /*RFValue*/ 12,
                marginRight: /*RFValue*/ 16,
                color:'#000'
              }}
            >
              三级
            </Text>
            {selectedCategory2.children.map((category3, index) => {
              return (
                <Category2Btn
                  key={index}
                  style={selectedCategory3 == category3.id && styles.selected2}
                  active={
                    selectedCategory3 && selectedCategory3 == category3.id
                  }
                  onPress={() => {
                    setSelectedCategory3(
                      selectedCategory3 === category3.id ? null : category3.id
                    );
                    setSelectedCommonCategory(null);
                    if (selectedCategory3 !== category3.id) {
                      updateSelectedCategoryId({ ...category3, eventType: 3 });
                    } else
                      updateSelectedCategoryId({
                        ...selectedCategory2,
                        eventType: 2,
                      });
                  }}
                >
                  {category3.name}
                </Category2Btn>
              );
            })}
          </S.Buttons2Wrapper>
        </S.Container3>
      )}

      {commonCategorys.length > 0 && (
        <S.Container2
          horizontal
          showsHorizontalScrollIndicator={false}
          style={{
            borderTopWidth: /*RFValue*/ 1,
            borderTopColor: "rgba(229, 229, 234, 1)",
            paddingBottom: /*RFValue*/ 16,
            paddingRight: /*RFValue*/ 16,
          }}
        >
          <S.Buttons2Wrapper>
            <Text
              style={{
                fontFamily: "HarmonyOS_Sans_SC_Regular",
                fontSize: /*RFValue*/ 12,
                marginRight: /*RFValue*/ 16,
                color:'#000'
              }}
            >
              常用
            </Text>
            {commonCategorys.map((category) => {
              return (
                <Category2Btn
                  style={
                    selectedCommonCategory === category.id && styles.selected2
                  }
                  active={selectedCommonCategory === category.id}
                  onPress={() => {
                    setSelectedValue(null);
                    setSelectedCategory2(null);
                    setSelectedCategory3(null);
                    setSelectedCommonCategory(
                      selectedCommonCategory === category.id
                        ? null
                        : category.id
                    );
                    if (selectedCommonCategory !== category.id) {
                      updateSelectedCategoryId(category);
                    } else {
                      updateSelectedCategoryId(null);
                    }
                  }}
                  key={category.id}
                >
                  {category.eventName}
                </Category2Btn>
              );
            })}
          </S.Buttons2Wrapper>
        </S.Container2>
      )}
    </S.Container>
  );
};

const styles = StyleSheet.create({
  selected: {
    backgroundColor: "rgba(247, 247, 247, 1)",
    height: /*RFValue*/ 36,
    borderBottomLeftRadius: 0,
    borderBottomRightRadius: 0,
    color: "rgba(142, 142, 147, 1)",
  },
  selected2: {
    backgroundColor: "rgba(78, 112, 172, 0.16)",
  },
});
